package com.manager.common.job;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.manager.common.constant.SystemConstant;
import com.manager.common.utils.DataTools;
import com.manager.model.LinuxBaseMonitor;
import com.manager.model.LinuxTcpInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Component
public class IntervalGetLinuxBaseUseInfo {

    @Value("${linux.ssh.ip}")
    private String ip;

    @Value("${linux.ssh.port}")
    private Integer port;

    @Value("${linux.ssh.password}")
    private String password;

    @Value("${linux.ssh.user.name}")
    private String userName;

    @Scheduled(fixedDelay = 10000)
    public void run() {
        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        ChannelExec channelExec = null;
        try {
            String[] commands = {
                    "df -h --total | grep 'total' | awk '{print $2,$3,$4,$5}' | sed 's/G//g' | sed 's/%//g'",
                    "free -h | grep 'Mem' | awk '{print $2,$4}' | sed 's/G//g'",
                    "vmstat | awk 'END {print $15}'",
                    "sar -n DEV 1 2 | grep 'Average' | awk 'NR >1 {print sum+=$5,n+=$6}' | awk  'END {print}'",
                    "lscpu | grep \"CPU MHz\" | awk '{print $3}'",
                    "netstat -antp | grep tcp | awk '{print $1, $2,$3,$4,$5,$6,$7,$8,$9,$10}'"};
            session = jsch.getSession(userName, ip, port);
            session.setPassword(password);

            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");

            session.setConfig(sshConfig);

            session.connect(60 * 1000);

            String buffer;
            InputStreamReader isr = null;
            BufferedReader reader = null;
            List<LinuxTcpInfo> linuxTcpInfoList = null;
            while (true) {
                linuxTcpInfoList = new ArrayList<>();
                LinuxBaseMonitor linuxBaseMonitor = new LinuxBaseMonitor();
                for (int i = 0; i < commands.length; i++) {
                    channel = session.openChannel("exec");
                    channelExec = (ChannelExec) channel;

                    String command = commands[i];
                    channel.setInputStream(null);
                    channelExec.setCommand(command);
                    channelExec.connect();

                    InputStream successIn = channelExec.getInputStream();

                    isr = new InputStreamReader(successIn, StandardCharsets.UTF_8);
                    reader = new BufferedReader(isr);
                    InputStream errorIn = channelExec.getErrStream();
                    LinuxTcpInfo linuxTcpInfo = null;
                    while ((buffer = reader.readLine()) != null) {
                        String[] arr = buffer.split(" ");
                        if (i == 0) {
                            linuxBaseMonitor.setTotalStorage(new BigDecimal(arr[0]));
                            linuxBaseMonitor.setUsedStorage(new BigDecimal(arr[1]));
                            linuxBaseMonitor.setFreeStorage(new BigDecimal(arr[2]));
                            linuxBaseMonitor.setUsedStoragePercent(new BigDecimal(arr[3]));
                        } else if (i == 1) {
                            linuxBaseMonitor.setMemoryTotal(new BigDecimal(arr[0]));
                            linuxBaseMonitor.setFreeMemory(new BigDecimal(arr[1]));
                            linuxBaseMonitor.setUsedMemory(linuxBaseMonitor.getMemoryTotal().subtract(linuxBaseMonitor.getFreeMemory()));
                            linuxBaseMonitor.setUsedMemoryPercent(ca(linuxBaseMonitor.getMemoryTotal(), linuxBaseMonitor.getUsedMemory()));
                        } else if (i == 2) {
                            linuxBaseMonitor.setUsedCpuPercent(new BigDecimal(100).subtract(new BigDecimal(arr[0])));
                            linuxBaseMonitor.setFreeCpuPercent(new BigDecimal(arr[0]));
                        } else if (i == 3) {
                            linuxBaseMonitor.setNetworkIn(new BigDecimal(arr[0]));
                            linuxBaseMonitor.setNetworkOut(new BigDecimal(arr[1]));
                        } else if (i == 4) {
                            BigDecimal result = new BigDecimal(arr[0]).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                            linuxBaseMonitor.setCpuGHZ(result);
                        } else if (i == 5) {
                            linuxTcpInfo = new LinuxTcpInfo();
                            linuxTcpInfo.setProtocolName(arr[0]);
                            linuxTcpInfo.setRecv(new BigDecimal(arr[1]));
                            linuxTcpInfo.setSend(new BigDecimal(arr[2]));
                            linuxTcpInfo.setLocalAddress(arr[3]);
                            linuxTcpInfo.setRemoteAddress(arr[4]);
                            linuxTcpInfo.setState(arr[5]);
                            StringBuffer stringBuffer = new StringBuffer();
                            for (int j = 6; j < arr.length; j++) {
                                stringBuffer.append(arr[j]).append(" ");
                            }
                            linuxTcpInfo.setPid(stringBuffer.toString().trim());
                            linuxTcpInfoList.add(linuxTcpInfo);
                        }
                    }
                    isr.close();
                    reader.close();
                    channelExec.disconnect();
                    channel.disconnect();
                }
                DataTools.addLinuxBaseMonitor(linuxBaseMonitor);
                DataTools.addCacheLinuxMonitor(SystemConstant.LINUX_TCP_MONITOR_LIST, linuxTcpInfoList);
                Thread.sleep(1000);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelExec != null) {
                channelExec.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }

    private BigDecimal ca(BigDecimal total, BigDecimal used) {
        BigDecimal result = used.divide(total, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
        return result;
    }
}


